<?php


namespace App\Http\Service\Auth;


use App\Config\CacheConfig;
use App\Enum\APIEnum;
use App\Exceptions\APIHttpException;
use App\Http\Library\Zws;
use App\Http\Model\Auth\LoginModel;
use Illuminate\Support\Facades\Cache;

class LoginService
{

    /**
     * pc-登录:获取指定token对应登录信息
     *
     * @param string $token
     *
     * @return array|null
     * @throws APIHttpException
     */
    public static function token(string $token)
    {
        $token = explode(' ', $token);
        $No = isset($token[0]) ? $token[0] : '';
        $token = isset($token[1]) ? $token[1] : '';
        /*解析登录信息*/
        $sslDecode = sslDecode($token, config('app.key'));
        if (empty($sslDecode)) {
            throw new APIHttpException(APIEnum::LOGIN_VOID['msg'], APIEnum::LOGIN_VOID['code']);
        }
        /*检查Token.No与{$No}是否一致*/
        if (empty($sslDecode['No']) || $sslDecode['No'] !== $No) {
            throw new APIHttpException(APIEnum::LOGIN_VOID['msg'], APIEnum::LOGIN_VOID['code']);
        }
        /*Token是否过期*/
        if ((time() - strtotime($sslDecode['ctime'])) > $sslDecode['ttl']) {
            throw new APIHttpException('Token已过期, 请重新登录', APIEnum::LOGIN_VOID['code']);
        }
        /*从缓存读取登录人信息*/
        $cacheAuth = CacheConfig::AUTH_PC_LOGIN;
        $info = Cache::get("{$cacheAuth}:{$sslDecode['uid']}");
        if (empty($info['id'])) {
            throw new APIHttpException(APIEnum::LOGIN_VOID['msg'], APIEnum::LOGIN_VOID['code']);
        }
        /*查询当前登录用户最新的信息*/
        $admin = LoginModel::admin($info['workcode']);
        if (empty($admin)) {
            throw new APIHttpException(APIEnum::LOGIN_NOT_ADMIN['msg'], APIEnum::LOGIN_NOT_ADMIN['code']);
        }
        /*账号状态检查*/
        if ($admin['is_disable'] !== 0) {
            //禁用后清除token，退出登录
            self::logout($sslDecode['uid']);
            throw new APIHttpException('管理员账号未启用', APIEnum::LOGIN_NOT_ADMIN['code']);
        }
        return array_merge($admin, ['uniqid' => $sslDecode['uid']]);
    }


    /**
     * PC-SSO-退出登录
     *
     * @param string $uniqid
     *
     * @return bool
     */
    public static function logout(string $uniqid)
    {
        $cacheAuth = CacheConfig::AUTH_PC_LOGIN;
        return Cache::forget("{$cacheAuth}:{$uniqid}");
    }


    /**
     * PC-SSO-登录
     *
     * @param string $workcode
     *
     * @return array
     * @throws APIHttpException
     */
    public static function login(string $workcode)
    {
        /*查询员工信息*/
        $user = LoginModel::login($workcode);
        /*没有找到管理员*/
        if (empty($user)) {
            throw new APIHttpException(APIEnum::LOGIN_NOT_ADMIN['msg'], APIEnum::LOGIN_NOT_ADMIN['code']);
        }
        if ($user['is_disable'] !== 0) {
            throw new APIHttpException('您的账号被禁用', APIEnum::LOGIN_NOT_ADMIN['code']);
        }
        /*生成一个登录token*/
        $user['uniqid'] = $workcode . ':' . uniqid(true);
        $user['time'] = date('Y-m-d H:i:s');
        $No = $workcode;
        /*token记录信息*/
        $user['token'] = sslEncode([
            'No'    => $No,
            'uid'   => $user['uniqid'],
            'ttl'   => config('ext.login_ttl') * 3600,
            'ctime' => $user['time'],
        ], config('app.key'));
        $cacheAuth = CacheConfig::AUTH_PC_LOGIN;
        /*结果写入缓存*/
        Cache::add("{$cacheAuth}:{$user['uniqid']}", $user, config('ext.login_ttl') * 3600);
        return [
            /*
             * Token生成规则:{No} {$token}
             * Nginx会截取{No}写入日志
             * */
            'token'    => "{$No} {$user['token']}",
            'workcode' => $user['workcode'],
            'username' => $user['username'],
        ];
    }


    /**
     * 获取用户信息
     *
     * @param $token
     *
     * @return null
     * @throws APIHttpException
     */
    public static function user($token)
    {
        if (empty($token)) {
            return null;
        }
        $cacheTicket = CacheConfig::ZWS_SSO_TOKEN;
        $md5Token = sha1($token);
        $exist = Cache::get("{$cacheTicket}:{$md5Token}");
        if (!empty($exist)) {
            throw new APIHttpException(APIEnum::LOGIN_EXPIRE['msg'], APIEnum::LOGIN_EXPIRE['code']);
        }
        Cache::add("{$cacheTicket}:{$md5Token}", 1, 3600 * 2);
        /*SSO-身份认证*/
        $user = Zws::verify($token);
        return empty($user['workcode']) ? null : $user['workcode'];
    }


}





/**
 * LoginService.php
 *
 * 说明:
 *
 * 修改历史
 * ----------------------------------------
 * 2021/3/10 17:34:00   操作:创建
 **/
